<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>DStation后台管理</title>

    <!-- Bootstrap Core CSS -->
    <link th:href="@{/boostrapTemplatResources/vendor/bootstrap/css/bootstrap.min.css}" rel="stylesheet">

    <!-- MetisMenu CSS -->
    <link th:href="@{/boostrapTemplatResources/vendor/metisMenu/metisMenu.min.css}" rel="stylesheet">

    <!-- Custom CSS -->
    <link th:href="@{/boostrapTemplatResources/dist/css/sb-admin-2.css}" rel="stylesheet">

    <!-- Morris Charts CSS -->
    <link th:href="@{/boostrapTemplatResources/vendor/morrisjs/morris.css}" rel="stylesheet">

    <!-- Custom Fonts -->
    <link th:href="@{/boostrapTemplatResources/vendor/font-awesome/css/font-awesome.min.css}" rel="stylesheet" type="text/css">

    <!-- boostrap table -->
    <link th:href="@{/boostrap_table/css/bootstrap-table.min.css}" rel="stylesheet">
    <link th:href="@{/boostrap_table/css/jquery.treegrid.min.css}" rel="stylesheet">
</head>

<body>

<nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0">
    <div th:include="admin/header :: header"></div>
    <div th:include="admin/sidebar :: sidebar"></div>
</nav>

<div id="wrapper">
    <!-- 主界面显示D站介绍信息 -->
    <div id="page-wrapper">
        <!-- 存放视频的分类信息的table -->
        <br>
        <a class="btn btn-primary btn-xs" style="margin: 10px auto" onclick="add()"><i class="fa fa-plus" ></i> 新增</a>
        <table id="table">

        </table>
    </div>
    <!-- 修改数据模态框（Modal） -->
    <form method="post" class="form-horizontal" role="form" onsubmit="return update_submit()">
        <div class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-labelledby="updateModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                            &times;
                        </button>
                        <h4 class="modal-title" id="updateModalLabel">
                            修改类别
                        </h4>
                    </div>
                    <div class="modal-body" style="height: 100%;">
                        <div class="form-group">
                            <label  class="col-sm-3 control-label">名称</label>
                            <div class="col-sm-7">
                                <input type="text" class="form-control"  name="update_description" id="update_description"
                                >
                                </input>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button class="btn btn-primary" type="submit" >提交</button>
                        <span id="tip"></span>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal -->
        </div>

    </form>
    <!-- 增加数据模态框（Modal） -->
    <form method="post" class="form-horizontal" role="form" onsubmit="return add_submit()">
        <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="updateModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                            &times;
                        </button>
                        <h4 class="modal-title" id="addModalLabel">
                            新增类别
                        </h4>
                    </div>
                    <div class="modal-body" style="height: 100%;">
                        <div class="form-group">
                            <label class="col-sm-3 control-label">父类</label>
                            <div class="col-sm-7">
                                <select data-placeholder="选择父类标签" class="form-control" name="project_name" id="project_name">
                                    <option value="0" selected="selected">请选择父类标签</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-3 control-label">名称</label>
                        <div class="col-sm-7">
                            <input type="text" class="form-control"  name="add_description" id="add_description"
                            >
                            </input>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button class="btn btn-primary" type="submit" >提交</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal -->
        </div>
    </form>

</div>
<!-- /#wrapper -->

<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<script th:src="@{/boostrapTemplatResources/js/html5shiv.js}"></script>
<script th:src="@{/boostrapTemplatResources/js/respond.min.js}"></script>

<!-- jQuery -->
<script th:src="@{/boostrapTemplatResources/vendor/jquery/jquery.min.js}"></script>

<!-- Bootstrap Core JavaScript -->
<script th:src="@{/boostrapTemplatResources/vendor/bootstrap/js/bootstrap.min.js}"></script>

<!-- Metis Menu Plugin JavaScript -->
<script th:src="@{/boostrapTemplatResources/vendor/metisMenu/metisMenu.min.js}"></script>

<!-- Morris Charts JavaScript -->
<script th:src="@{/boostrapTemplatResources/vendor/raphael/raphael.min.js}"></script>
<script th:src="@{/boostrapTemplatResources/vendor/morrisjs/morris.min.js}"></script>
<script th:src="@{/boostrapTemplatResources/data/morris-data.js}"></script>

<!-- Custom Theme JavaScript -->
<script th:src="@{/boostrapTemplatResources/dist/js/sb-admin-2.js}"></script>

<!-- boostrap table -->
<script th:src="@{/boostrap_table/js/bootstrap-table.min.js}"></script>
<script th:src="@{/boostrap_table/js/bootstrap-table-treegrid.js}"></script>
<script th:src="@{/boostrap_table/js/jquery.treegrid.min.js}"></script>

<!-- swal alert -->
<script th:src="@{/js/sweetAlert.js}"></script>
</body>

<script type="text/javascript">
    var $table = $('#table');
    var data = null;

    //1. 拿到全部的视频分类信息
    $.ajax(
        {
            type: "GET",
            url: "/classificationInfo/queryAllClassifyInfos",
            async: false,
            cache: true,
            success: function (jsonObject) {
                if(jsonObject["res"] == "null") {
                    swal("Error", "未添加任何信息", "error");
                } else {
                    data = JSON.parse(jsonObject["data"]);  //存入jsonArray数据
                }
            },
            error: function (jsonObject) {
                swal("Error", "网络错误，请联系管理员！", "error");
            }
        }
    );
    // 2. 加载boostrap的树插件
    $(function() {
        $table.bootstrapTable({
            data:data,
            idField: 'classificationId',
            dataType:'jsonp',
            columns: [
                { field: 'check', checkbox: true, formatter: function (value, row, index) {
                        if (row.check == true) {
                            // console.log(row.serverName);
                            //设置选中
                            return { checked: true };
                        }
                    }
                },
                // {field: 'classificationId', title: '编号', sortable: true, align: 'center'},
                { field: 'description', title: '描述' },
                // { field: 'status', title: '状态', sortable: true, align: 'center', formatter: 'statusFormatter' },
                { field: 'createDate', title: '创建日期', align: 'center' },
                { field: 'operate', title: '操作', align: 'center', events : operateEvents, formatter: 'operateFormatter' },
            ],

            // bootstrap-table-treegrid.js 插件配置 -- start

            //在哪一列展开树形
            treeShowField: 'description',
            //指定父id列
            parentIdField: 'parentId',

            onResetView: function(data) {
                //console.log('load');
                $table.treegrid({
                    initialState: 'collapsed',// 所有节点都折叠
                    // initialState: 'expanded',// 所有节点都展开，默认展开
                    treeColumn: 1,
                    // expanderExpandedClass: 'glyphicon glyphicon-minus', //图标样式
                    // expanderCollapsedClass: 'glyphicon glyphicon-plus',
                    onChange: function() {
                        $table.bootstrapTable('resetWidth');
                    }
                });

                //只展开树形的第一级节点
                $table.treegrid('getRootNodes').treegrid('expand');

            },
            onCheck:function(row){
                var datas = $table.bootstrapTable('getData');
                // 勾选子类
                selectChilds(datas,row,"classificationId","parentId",true);

                // 勾选父类
                //selectParentChecked(datas,row,"classificationId","parentId");

                // 刷新数据
                $table.bootstrapTable('load', datas);
            },

            onUncheck:function(row){
                var datas = $table.bootstrapTable('getData');
                selectChilds(datas,row,"classificationId","parentId",false);
                $table.bootstrapTable('load', datas);
            },
            // bootstrap-table-treetreegrid.js 插件配置 -- end
        });
    });

    //3. 定义格式化函数
    // 格式化按钮
    function operateFormatter(value, row, index) {
        return [
            '<button type="button" class="btn btn-primary btn-xs" onclick="update(\''+index+'\')" style="margin-right:15px;"><i class="fa fa-pencil-square-o" ></i> 修改</button>'
        ].join('');

    }
    // 格式化类型
    function typeFormatter(value, row, index) {
        if (value === 'menu') { return '菜单'; }
        if (value === 'button') { return '按钮'; }
        if (value === 'api') { return '接口'; }
        return '-';
    }
    // 格式化状态
    function statusFormatter(value, row, index) {
        if (value === 1) {
            return '<span class="label label-success">正常</span>';
        } else {
            return '<span class="label label-default">锁定</span>';
        }
    }

    //初始化操作按钮的方法
    window.operateEvents = {
        // 'click .RoleOfadd': function (e, value, row, index) {
        //     add(row.id);
        // },
        'click .RoleOfdelete': function (e, value, row, index) {
            alert(row.length);
            del(row.id);
        },
        'click .RoleOfedit': function (e, value, row, index) {
            alert(row.toString());
            update(row.id);
        }
    };
</script>
<script>
    var edit_data = null;
    /**
     * 选中父项时，同时选中子项
     * @param datas 所有的数据
     * @param row 当前数据
     * @param id id 字段名
     * @param pid 父id字段名
     */
    function selectChilds(datas,row,id,pid,checked) {
        for(var i in datas){
            if(datas[i][pid] == row[id]){
                datas[i].check=checked;
                selectChilds(datas,datas[i],id,pid,checked);
            };
        }
    }

    function selectParentChecked(datas,row,id,pid){
        for(var i in datas){
            if(datas[i][id] == row[pid]){
                datas[i].check=true;
                selectParentChecked(datas,datas[i],id,pid);
            };
        }
    }

    function test() {
        var selRows = $table.bootstrapTable("getSelections");
        if(selRows.length == 0){
            alert("请至少选择一行");
            return;
        }

        var postData = "";
        $.each(selRows,function(i) {
            postData += this.id;
            if (i < selRows.length - 1) {
                postData += "， ";
            }
        });
        alert("你选中行的 id 为："+postData);

    }

    function update(index) {
        var rows = $table.bootstrapTable("getData");
        edit_data = rows[index];
        console.log(edit_data);
        $("#update_description").val(edit_data['description']);
        $('#updateModal').modal();
    }
    function update_submit()
    {
        var date = new Date().toLocaleDateString();
        var description = $("#update_description").val();

        if(!description)
        {
            alert('不能为空！');
            return false;
        }

        $.ajax(
            {
                url: "/classificationInfo/edit",
                data:{"classificationId":edit_data['classificationId'],
                    "parentId":edit_data['parentId'],
                    "description":description
                },
                type: "post",
                beforeSend:function()
                {
                    $("#tip").html("<span style='color:blue'>正在处理...</span>");
                    return true;
                },
                success:function()
                {
                    var msg = "修改";
                    $("#tip").html("<span style='color:blueviolet'>恭喜，" +msg+ "成功！</span>");
                    alert(msg + "成功");
                    location.reload();
                },
                error:function()
                {
                    alert('请求出错');
                },
                complete:function()
                {
                    $('#acting_tips').hide();
                }
            });
        return false;
    }

</script>
<script type="text/javascript">
    var add_data=null;
    var parent_date=null;

    function add() {
        $.ajax(
            {
                type: "GET",
                url: "/classificationInfo/queryAllParentClassifys",
                async: false,
                cache: true,
                success: function (jsonObject) {
                    if(jsonObject["res"] == "null") {
                        swal("Error", "无父类标签", "error");
                    } else {
                        parent_date = JSON.parse(jsonObject["data"]);  //存入jsonArray数据
                    }
                },
                error: function (jsonObject) {
                    swal("Error", "网络错误，请联系管理员！", "error");
                }
            }
        );
        for (var i = 0; i < parent_date.length; i++) {
            var newOption = document.createElement("option");
            newOption.value = parent_date[i].classificationId;
            newOption.text = parent_date[i].description;
            document.getElementById("project_name").options.add(newOption);
        }
        $('#addModal').modal();
    }

    function add_submit() {
        var parentId = $("#project_name").val();
        var description = $("#add_description").val();

        if(!description)
        {
            alert('不能为空！');
            return false;
        }

        $.ajax(
            {
                url: "/classificationInfo/add",
                data:{
                    "parentId":parentId,
                    "description":description
                },
                type: "post",
                success:function()
                {
                    var msg = "添加";
                    alert(msg + "成功");
                    location.reload();
                },
                error:function()
                {
                    alert('请求出错');
                }
            });
        return false;
    }
</script>
</html>
